var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser') // 处理前端传过来的数据
// 处理token 的工具函数
const jwtUtils = require('./utils/jwtUtils')
// 使用jwt签名
var jwt = require('jsonwebtoken')
var fs = require('fs')

var logger = require('morgan')

var app = express()
// 自定义跨域中间件
var allowCors = function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-type,Content-Length,Authorization,Accept,X-Requested-Width");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    if (req.method == "OPTIONS") { return res.end(); };
    next();
}
app.use(allowCors) //使用跨域中间件

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

app.use(logger('dev'))

// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({
//   extended: false
// }));
// 下面两项设置文件上传的大小限制为50m，不写的话可能会因为文件超过3m而报413
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))

app.use(cookieParser())
// 这里配置了静态资源，所以访问图片直接http://localhost:3001/images/homeList1.png可以拿到
app.use(express.static(path.join(__dirname, 'public')))

var indexRouter = require('./routes/index')
var usersRouter = require('./routes/users')
var resumesRouter = require('./routes/resumes')
var collectionRouter = require('./routes/collections')
var resumeTemplatesRouter = require('./routes/resumeTemplates')
var imgRouter = require('./routes/imgs')
var clubsRouter = require('./routes/clubs')
var articlesRouter = require('./routes/articles')
var appListsRouter = require('./routes/appLists')
var bannersRouter = require('./routes/banners')
var sidebarAdImgsRouter = require('./routes/sidebarAdImgs')
var linksRouter = require('./routes/links')
var commentsRouter = require('./routes/comments')
var planListsRouter = require('./routes/planLists') //计划
var blogsRouter = require('./routes/blogs') //博客

// 全局拦截【token校验】--该代码要放在定义路由之上，不然直接走定义路由了，拦截不到
app.use(function (req, response, next) {
    // 路由白名单，该路由不需要去拦截
		// let userList = ['user/login']
	if (req.url.search('/users/login') != -1) {
		next()
	} else {
        
		// 如果不是登录接口
		var isToken = jwtUtils.checkTokenByRequest(req)
		// 如果获取的token 不合格，则给出提示信息
		if (isToken=='1') {
			response.status(200).json({
				code: '401',
				message: 'token失效',
                data: null,
                success: false
			})
			return false
		}else{
            next()
        }
	}
})

app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/resumes', resumesRouter)
app.use('/resumeTemplates', resumeTemplatesRouter)
app.use('/collections', collectionRouter)
app.use('/imgs', imgRouter)
app.use('/clubs', clubsRouter)
app.use('/articles', articlesRouter) //文章
app.use('/appLists', appListsRouter) //软件
app.use('/banners', bannersRouter) //轮播图
app.use('/sidebarAdImgs', sidebarAdImgsRouter) //侧边广告图
app.use('/links', linksRouter) //友情链接
app.use('/comments', commentsRouter) //评论

app.use('/planLists', planListsRouter) //计划
app.use('/blogs', blogsRouter) //博客

// 全局拦截，拦截不存在的地址【404】 该代码应该放在文件最下面，先走定义路由，不在定义路由才走404
app.use('*', function (req, res, next) {
	res.locals.message = '接口地址不存在'
	res.locals.status = `当前请求地址为：${req.headers.host}${req.baseUrl}，请求方式为：${req.method}`
	res.locals.stack = '1.请查看接口地址是否拼写错误！ 2.请查看请求方式是否正确'
	res.render('error')
	// next(createError(404));
})
module.exports = app
